package com.lagou.job.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.lagou.job.pojo.User;
import com.lagou.job.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;

/**
 * 登录控制类
 * @author yzh
 */
@RestController
@RequestMapping("login")
public class LoginController {

    @Autowired
    private UserService<User> userService;

    /**
     * 校验登录状态
     * @return
     */
    @GetMapping("checkLogin")
    public R checkLogin(HttpServletRequest request) {
        R result = null;
        try {
            Object user = request.getSession().getAttribute("user");
            if(user != null && ((User) user).getUserId().equals(Integer.parseInt(request.getParameter("userId")))) {
                result = R.ok(user);
            } else {
                result = R.failed("用户未登录");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = R.failed("校验登录出错");
        }
        return result;
    }

    /**
     * 登录
     * @return
     */
    @GetMapping("toLogin")
    public R toLogin(User user, HttpServletRequest request) {
        R result = null;
        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_name", user.getUserName());
            queryWrapper.eq("user_password", user.getUserPassword());
            User newUser = userService.getOne(queryWrapper);
            if(newUser != null) {
                request.getSession().setAttribute("user", newUser);
                result = R.ok(newUser);
            } else {
                result = R.failed("账户名或密码错误");
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result = R.failed("登录出错");
        }
        return result;
    }
}
